
package lt.andro.seimorinkimai2012;

import java.io.IOException;
import java.net.URL;

import lt.andro.utils.GoogleAnalyticsEventsHelper;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;

final class WebPageLoaderTask extends AsyncTask<String, Void, Elements> {
    private static final String TAG = WebPageLoaderTask.class.getCanonicalName();
    private final WebView mView;
    private final Activity mActivity;
    private String baseUri;
    private final GoogleAnalyticsEventsHelper mGoogleAnalyticsEventsHelper;
    private String mUrl;

    WebPageLoaderTask(WebView view, Activity activity,
            GoogleAnalyticsEventsHelper googleAnalyticsEventsHelper) {
        this.mView = view;
        this.mActivity = activity;
        this.mGoogleAnalyticsEventsHelper = googleAnalyticsEventsHelper;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ((SherlockActivity)mActivity).setSupportProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected Elements doInBackground(String... params) {
        mUrl = params[0];
        Log.d(TAG, "Loading url: " + mUrl);
        mGoogleAnalyticsEventsHelper.trackPageView(mUrl);

        Document doc = null;
        try {
            doc = Jsoup.parse(new URL(mUrl).openStream(), "utf-8", mUrl);
            baseUri = doc.baseUri();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        Elements ele = null;
        ele = doc.select("div#contentCenter");
        if (ele.size() == 0) {
            ele = doc.getAllElements();
        }
        return ele;

    }

    @Override
    protected void onPostExecute(Elements result) {
        ((SherlockActivity)mActivity).setSupportProgressBarIndeterminateVisibility(false);
        if (result == null) {
            if (!mUrl.equals(MainActivity.HOME_URL)) {
                Toast.makeText(mActivity.getApplicationContext(),
                        R.string.web_view_client_failed_to_load, Toast.LENGTH_LONG).show();
            } else {
                mView.loadUrl(MainActivity.HOME_URL);
            }
            return;
        }
        String data = result.toString();

        String mimeType = "text/html";
        String encoding = "utf-8";
        String baseUrl = baseUri.toString();
        String historyUrl = mUrl;
        mView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
        super.onPostExecute(result);
    }
}
